package com.godme.concurrent.pattern;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SingleThreadExecutionPattern {

    public static class NumberResource {
        private Integer number = 0;
        private Integer printIndex = 0;
        private Lock lock = new ReentrantLock();

        private void add() {
            this.number++;
        }

        private Integer get() {
            return this.number;
        }

        public void showNumber() throws InterruptedException {

            if (printIndex > 100) System.exit(0);
            lock.lock();
            Integer number1 = this.get();
            this.add();
            Thread.sleep(5);
            Integer number2 = this.get();
            lock.unlock();
            if ((number1 + 1) == number2) {
                System.out.println(Thread.currentThread().getName() + " => 递增--正确--：" + number1 + " ***** " + number2);
            } else {
                System.out.println(Thread.currentThread().getName() + " => 递增**异常**：" + number1 + " ***** " + number2);
            }
            printIndex++;

        }
    }

    static class SingleThread extends Thread {
        private final NumberResource numberResource;

        public SingleThread(NumberResource numberResource){
            this.numberResource = numberResource;
        }

        @Override
        public void run() {
           try{
               while (true){
                   numberResource.showNumber();
               }
           }catch (Exception e){
               e.printStackTrace();
           }
        }
    }

    public static void main(String[] args) {
        NumberResource numberResource = new NumberResource();
        new SingleThread(numberResource).start();
        new SingleThread(numberResource).start();

    }
}
